#include <stdlib.h>
#include <stdio.h>
#include "sqlite3.h"
#include "database.h"
#include "VIP_insert.h"


// 增加会员
int VIP_insert(VIP *v){
    char sql[256];
    char *errmsg=NULL;
    printf("-----------------------------------------------\n");
    sprintf(sql,"insert into create_vip_user(account_id, password, name, age, sex, phone, vip_level, status, address) values(%d, '%s', '%s', %d, '%s', '%s', %d, %d, '%s');",
            v->account_id,v->password,v->name,v->age,v->sex,v->phone,v->vip_level,v->status,v->address);
//    printf("sql: %s\n",sql);
    int rc= sqlite3_exec(db,sql,NULL,NULL,&errmsg);
    if(rc!=SQLITE_OK){
        fprintf(stderr,"VIP_insert:增加会员失败：%s\n",errmsg);
        sqlite3_free(errmsg);
        return -1;
    }
    printf("VIP_insert:插入数据成功！\n");
    return 0;
}

// 删除会员
int VIP_delete(int id){
    char sql[256];
    char *errmsg=NULL;
    sprintf(sql,"delete from create_vip_user where user_vip_id=%d",id);
    int rc= sqlite3_exec(db,sql,NULL,NULL,&errmsg);
    if(rc!=SQLITE_OK){
        fprintf(stderr,"VIP_delete:删除会员失败：%s\n",errmsg);
        sqlite3_free(errmsg);
        return -1;
    }
    printf("VIP_delete:第%d号会员删除成功！\n",id);
    return 0;
}

static int callback(void *data,int argc,char **argv,char **arg_col_name){
    (*(int *)data)++;
    static int row=0;
    if(row==0){
        for (int i = 0; i <argc ; ++i) {
            printf("|%s",arg_col_name[i]);
        }
        row=1;
        printf("|\n");
        printf("-------------------------------------------------------------\n");
    }
    for (int i = 0; i < argc; ++i) {
        printf("|%s",argv[i] ? argv[i] : "NULL");
    }
    printf("|\n");
    return 0;
}

// 查询会员信息
int VIP_query(){
    char *errmsg=NULL;
    int rowcount=0;
    const char *sql = "select * from create_vip_user;";
    int rc= sqlite3_exec(db,sql,callback,&rowcount,&errmsg);
    if(rc!=SQLITE_OK){
        fprintf(stderr,"VIP_query:查询失败：%s\n",errmsg);
        sqlite3_free(errmsg);
        return -1;
    }
    printf("VIP_query:查询成功！共查询到 %d 条会员数据\n", rowcount);
    return 0;
}
// 修改会员信息
int VIP_update(VIP *v){
    char sql[256];
    char *errmsg=NULL;
    sprintf(sql,"update create_vip_user set password='%s',name='%s',age=%d,sex='%s',phone='%s',vip_level=%d,status=%d,address='%s' where account_id=%d;",
            v->password,v->name,v->age,v->sex,v->phone,v->vip_level,v->status,v->address,v->account_id);
    int rc= sqlite3_exec(db,sql,NULL,NULL,&errmsg);
    if(rc!=SQLITE_OK){
        fprintf(stderr,"VIP_update修改会员信息失败：%s\n",errmsg);
        sqlite3_free(errmsg);
        return -1;
    }
    printf("VIP_update修改会员信息成功！\n");
    return 0;
}